package fun.configuration;

import java.awt.Font;
import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;


import org.lex.app.prefs.PropertyFileResourceMap;
import org.lex.app.prefs.ResourceMap;
import org.lex.utils.Codec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Config {
	private static ResourceMap instance = null;
	private static String CONFIG_FILE_NAME = "fun.xml";
	private static Logger log = LoggerFactory.getLogger(Config.class);

	public static final ResourceMap instance() {
		if (null == instance) {
			instance = new PropertyFileResourceMap(CONFIG_FILE_NAME);
		}
		return instance;
	}

	private Config() {
	}

	// get & set
	public static String getProperty(String key) {
		return instance().getString(key);
	}

	public static void setProperty(String key, String value) {
		instance().putString(key, value);
	}

	// convenient method for Font, Rectangle
	public static void setFont(String key, Font font) {
		instance().putString(key, Codec.encodeFont(font));
	}

	public static Font getFont(String key) {
		return Codec.decodeFont(instance().getString(key));
	}

	public static void setRectangle(String key, int x, int y, int width, int height) {
		setRectangle(key, new Rectangle(x, y, width, height));
	}

	public static void setRectangle(String key, Rectangle rec) {
		instance().putString(key, Codec.encodeRectangle(rec));
	}

	public static Rectangle getRectangle(String key) {
		return Codec.decodeRectangle(instance().getString(key));
	}

	// load & store from/to local file-system
	public static void loadConfigurationFromFile() {
		File file = new File(CONFIG_FILE_NAME);
		// config file missing : restore default
		if (false == file.exists()) {
			log.info("config file missing --> restore defaults");
			DefaultConfiguration.loadDefaultConfiguration(instance());
			storeConfigurationToFile();
		}
		// load from config file
		try {
			instance().load();
		} catch (Exception e) {
			log.error("load config file failed", e);
		}
	}

	public static void storeConfigurationToFile() {
		File file = new File(CONFIG_FILE_NAME);
		if (false == file.exists()) {
			try {
				log.info("config file missing -> create it");
				file.createNewFile();
				log.info("create success");
			} catch (IOException e) {
				log.error("create config file failed", e);
			}
		}
		try {
			instance().store();
		} catch (Exception e) {
			log.error("save config file failed", e);
		}
	}
}
